package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.framework.config.properties.HuaWeiIotConfigProperties;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.IotMsgNotifyData;
import com.zzyl.nursing.vo.IotMsgService;
import com.zzyl.nursing.vo.ProductVo;
import com.zzyl.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 设备信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-23
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 查询设备信息
     * 
     * @param id 设备信息主键
     * @return 设备信息
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备信息列表
     * 
     * @param device 设备信息
     * @return 设备信息
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备信息
     * 
     * @param device 设备信息
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备信息
     * 
     * @param device 设备信息
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备信息
     * 
     * @param ids 需要删除的设备信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备信息信息
     * 
     * @param id 设备信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private IoTDAClient client;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {

        try {
            //1. 调用IOT平台接口查询产品列表
            ListProductsResponse response = client.listProducts(new ListProductsRequest());
            if(response.getHttpStatusCode()!= HttpStatus.HTTP_OK) {
                throw new BaseException("同步产品列表失败");
            }

            //2. 获取响应结果的产品列表
            List<ProductSummary> productSummaryList = response.getProducts();

            if(CollUtil.isNotEmpty(productSummaryList)) {
                //3. 将产品列表转为JSON字符串
                String jsonStr = JSONUtil.toJsonStr(productSummaryList);

                //4. 将JSON字符串存入Redis
                redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_KEY, jsonStr);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 查询全部产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //1. 从Redis查询产品列表的JSON字符串
        String jsonStr = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_KEY);
        if(StrUtil.isBlank(jsonStr)) {
            return Collections.emptyList();
        }

        //2. 将JSON字符串转为列表类型
        List<ProductSummary> productSummaryList = JSONUtil.toList(jsonStr, ProductSummary.class);

        //3. 将产品对象转为VO对象
        List<ProductVo> productVoList = productSummaryList.stream()
                .map(x -> ProductVo.builder().productKey(x.getProductId()).productName(x.getName()).build())
                .collect(Collectors.toList());

        return productVoList;
    }


    /**
     * 注册设备
     *
     * @param dto
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void register(DeviceDto dto) {
        //1. 判断设备名称是否重复
        Long countByDeviceName = this.lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()).count();
        if(countByDeviceName>0) {
            throw new BaseException("设备名称重复");
        }

        //2. 判断设备标识是否重复
        String nodeId = IdUtil.getSnowflakeNextIdStr();

        //3. 判断同一位置是否绑定过同样的产品 select count(*) from device
        // where binding_location=? and location_type=? and product_key=?
        Long countByLocation = this.lambdaQuery()
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getProductKey, dto.getProductKey())
                .count();
        if(countByLocation>0) {
            throw new BaseException("不要绑定同样设备");
        }

        //4. 注册设备到华为云IOT平台
        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();

        AddDevice addDevice = new AddDevice();
        addDevice.setNodeId(nodeId);//设备唯一标识
        addDevice.setDeviceName(dto.getDeviceName());//设备英文名
        addDevice.setDescription(dto.getNickname());//设备中文名
        addDevice.setProductId(dto.getProductKey());//产品key

        //设备密钥
        String secret = IdUtil.fastSimpleUUID();

        AuthInfo authInfo = new AuthInfo();
        authInfo.setSecret(secret);
        addDevice.setAuthInfo(authInfo);

        addDeviceRequest.setBody(addDevice);

        try {
            AddDeviceResponse response = client.addDevice(addDeviceRequest);
            if(response.getHttpStatusCode()!=HttpStatus.HTTP_CREATED) {
                throw new BaseException("注册失败到IOT平台失败");
            }

            String iotId = response.getDeviceId();//生成规则为"product_id" + "_" + "node_id"拼接而成

            //5. 设备表新增数据
            Device device = BeanUtil.toBean(dto, Device.class);
            device.setIotId(iotId); //设备唯一ID
            device.setNodeId(nodeId); //设备唯一标识
            device.setSecret(secret); //设备密钥
            device.setHaveEntranceGuard(dto.getNickname().contains("门禁") ? 1: 0 );//是否门禁

            String productId = dto.getProductKey();
            String productName = getProductNameFromCache(productId);
            if(StrUtil.isNotBlank(productName)) {
                device.setProductName(productName);//产品名称
            }
            this.save(device);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("注册失败到IOT平台失败");
        }
    }

    /**
     * 从缓存中获取产品名称
     * @param productId
     * @return
     */
    private String getProductNameFromCache(String productId) {
        String jsonStr = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_KEY);
        if(StrUtil.isBlank(jsonStr)) {
            return null;
        }

        List<ProductSummary> productSummaryList = JSONUtil.toList(jsonStr, ProductSummary.class);
        ProductSummary productSummary = productSummaryList.stream().filter(x -> productId.equals(x.getProductId())).findFirst().get();
        if(productSummary!=null) {
            return productSummary.getName();//产品名
        }
        return null;
    }

    @Autowired
    private HuaWeiIotConfigProperties huaWeiIotConfigProperties;

    @Autowired
    private ISysUserService sysUserService;


    /**
     * 查看设备详情
     *
     * @param iotId      设备ID
     * @param productKey 产品KEY
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId, String productKey) {
        //1. 查询表中设备
        Device device = this.lambdaQuery().eq(Device::getIotId, iotId)
                .eq(Device::getProductKey, productKey)
                .one();
        if(device==null) {
            throw new BaseException("表中设备不存在");
        }

        //2. 查询华为云IOTDA平台中设备详情
        ShowDeviceRequest showDeviceRequest = new ShowDeviceRequest();
        showDeviceRequest.withDeviceId(iotId);//设备唯一ID
        ShowDeviceResponse response = client.showDevice(showDeviceRequest);
        if(response.getHttpStatusCode()!=HttpStatus.HTTP_OK) {
            throw new BaseException("IOT平台中设备不存在");
        }

        //3. 合并数据
        DeviceDetailVo vo = BeanUtil.toBean(device, DeviceDetailVo.class);
        vo.setGmtCreate(device.getCreateTime());//创建时间
        vo.setRegion(huaWeiIotConfigProperties.getRegionId());//区域
        vo.setDeviceSecret(device.getSecret());//设备密钥
        Long sysUserId = Long.valueOf(device.getCreateBy());//创建人用户ID
        SysUser sysUser = sysUserService.selectUserById(sysUserId);
        vo.setCreator(sysUser.getUserName());//创建人名称
        vo.setDeviceStatus(response.getStatus());//设备在线状态
        vo.setFirmwareVersion(response.getFwVersion());//固件版本
        String activeTime = response.getActiveTime();//设备激活时间，格式：yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
        if(StrUtil.isNotBlank(activeTime)) {
            LocalDateTime gmtActive = OffsetDateTime.parse(activeTime)
                    .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            vo.setGmtActive(gmtActive);//设备激活时间 （只有第一次上报数据设备才会被激活）
        }
        return vo;
    }

    /**
     * 查看指定产品的已发布物模型中的功能定义详情
     *
     * @param dto
     */
    @Override
    public JSONObject queryProductModelInfo(DeviceDto dto) {
        //1. 调用IOT平台的接口查询产品
        ShowProductRequest showProductRequest = new ShowProductRequest();
        showProductRequest.withProductId(dto.getProductKey());
        ShowProductResponse showProductResponse = client.showProduct(showProductRequest);
        if(showProductResponse.getHttpStatusCode()!=HttpStatus.HTTP_OK) {
            throw new BaseException("产品在IOT平台不存在");
        }

        //2. 解析响应结果
        List<ServiceCapability> serviceCapabilityList = showProductResponse.getServiceCapabilities();
        if(CollUtil.isNotEmpty(serviceCapabilityList)) {
            ServiceCapability serviceCapability = serviceCapabilityList.get(0);
            JSONObject jsonObject = JSONUtil.parseObj(serviceCapability);
            return jsonObject;
        }
        return null;
    }


    /**
     * 查询指定设备的物模型运行状态(设备上报的数据)
     *
     * @param productKey
     * @param deviceName
     * @return
     */
    @Override
    public Map<String, Object> queryDevicePropertyStatus(String productKey, String deviceName) {
        //从表中查询设备信息
        Device device = this.lambdaQuery().eq(Device::getProductKey, productKey)
                .eq(Device::getDeviceName, deviceName)
                .one();
        if(device==null) {
            throw new BaseException("表中设备不存在");
        }

        //调用IOT云平台接口查询设备影子信息
        ShowDeviceShadowRequest showDeviceShadowRequest = new ShowDeviceShadowRequest();
        showDeviceShadowRequest.withDeviceId(device.getIotId());//设备ID
        ShowDeviceShadowResponse response = client.showDeviceShadow(showDeviceShadowRequest);
        if(response.getHttpStatusCode()!=HttpStatus.HTTP_OK) {
            throw new BaseException("没有上报数据");
        }

        //解析响应结果
        List<DeviceShadowData> shadowDataList = response.getShadow();
        if(CollUtil.isEmpty(shadowDataList)) {
            return Collections.emptyMap();
        }
        String eventTime = shadowDataList.get(0).getReported().getEventTime();//物模型属性数据上报时间，格式：20151212T121212Z
        if(StrUtil.isNotBlank(eventTime)) {
            LocalDateTime reportTime = OffsetDateTime.parse(eventTime,DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"))
                    .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            //上报的属性对象数据集合
            List<Map<String,Object>> propertyStatusInfoList = new ArrayList<>();
            JSONObject propertiesJSONObject = JSONUtil.parseObj(shadowDataList.get(0).getReported().getProperties());
            propertiesJSONObject.forEach((k,v)->{
                String propertyName = k; //上报的属性名
                Object propertyValue = v; //上报的属性值

                Map<String,Object> propertyMap = new HashMap<>();
                propertyMap.put("identifier",propertyName);
                propertyMap.put("value", propertyValue);
                propertyMap.put("time",reportTime);
                propertyStatusInfoList.add(propertyMap);
            });

            Map<String,Object> propertyStatusInfoMap = new HashMap<>();
            propertyStatusInfoMap.put("propertyStatusInfo",propertyStatusInfoList);

            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("list",propertyStatusInfoMap);

            return resultMap;
        }
        return null;
    }

    @Autowired
    private IDeviceDataService deviceDataService;

    /**
     * 处理解析后的消息数据
     *
     * @param notifyData
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void handleMessageData(IotMsgNotifyData notifyData) {
        //1. 判断设备是否存在
        String deviceId = notifyData.getHeader().getDeviceId();
        Device device = this.lambdaQuery().eq(Device::getIotId, deviceId).one();
        if(device==null) {
            throw new BaseException("设备不存在");
        }

        //2. 获取上报的服务信息
        List<IotMsgService> serviceList = notifyData.getBody().getServices();

        serviceList.forEach(x->{
            //3. 获取上报的物模型数据信息
            Map<String, Object> properties = x.getProperties();
            String eventTime = x.getEventTime(); //数据上报时间，时间格式：20251025T021057Z
            LocalDateTime alertTime = OffsetDateTime.parse(eventTime, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"))
                    .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            List<DeviceData> deviceDataList = properties.entrySet().stream().map(entry -> {
                String functionId = entry.getKey();
                Object dataValue = entry.getValue();
                DeviceData deviceData = DeviceData.builder()
                        .deviceName(device.getDeviceName())//设备名
                        .iotId(deviceId)//设备id
                        .nodeId(device.getNodeId())//节点id
                        .nickname(device.getNickname())//设备昵称
                        .productKey(device.getProductKey())//产品key
                        .productName(device.getProductName())//产品名
                        .functionId(functionId)
                        .dataValue(String.valueOf(dataValue))
                        .accessLocation(device.getBindingLocation())//绑定位置
                        .locationType(device.getLocationType())//位置类型
                        .physicalLocationType(device.getPhysicalLocationType())//物理位置
                        .alarmTime(alertTime) //数据上报时间
                        .build();
                return deviceData;
            }).collect(Collectors.toList());

//            List<DeviceData> deviceDataList = new ArrayList<>();
//            properties.forEach((k,v)->{
//                String functionId = k;//功能名（设备的物模型属性名）
//                Object dataValue = v; //属性上报的值
//
//                DeviceData deviceData = DeviceData.builder()
//                        .deviceName(device.getDeviceName())//设备名
//                        .iotId(deviceId)//设备id
//                        .nodeId(device.getNodeId())//节点id
//                        .nickname(device.getNickname())//设备昵称
//                        .productKey(device.getProductKey())//产品key
//                        .productName(device.getProductName())//产品名
//                        .functionId(functionId)
//                        .dataValue(String.valueOf(dataValue))
//                        .accessLocation(device.getBindingLocation())//绑定位置
//                        .locationType(device.getLocationType())//位置类型
//                        .physicalLocationType(device.getPhysicalLocationType())//物理位置
//                        .alarmTime(alertTime) //数据上报时间
//                        .build();
//                deviceDataList.add(deviceData);
//            });

            //4. 批量新增设备数据
            deviceDataService.saveBatch(deviceDataList);

            //5. 将设备最新上报的数据存入Redis中 （Hash类型，  大KEY：固定字符串   小KEY：设备ID   value: 上报数据的JSON字符串）
            redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_DATA_LATEST,deviceId,JSONUtil.toJsonStr(deviceDataList));
        });
    }
}
